<template>
  <div class="adress-add">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="100px"
      label-position="left"
      required
    >
      <el-form-item label="地址信息" prop="addressInfo">
        <div style="width: 500px;">
          <el-cascader size="medium" v-if="isShowAddressInfo" v-model="form.addressInfo" clearable :props="props"></el-cascader>
        </div>
      </el-form-item>

      <el-form-item label="详细地址" prop="detailed">
        <div style="width: 500px;">
          <el-input v-model="form.detailed" placeholder="请输入详细地址信息，如道路、门牌号、小区、楼栋号、单元等信息"></el-input>
        </div>
      </el-form-item>
      <el-form-item label="邮政编码" prop="zipCode">
        <div style="width: 500px;">
          <el-input v-model="form.zipCode" placeholder="请填写邮编"></el-input>
        </div>
      </el-form-item>
      <el-form-item label="收货人姓名" prop="consignee">
        <div style="width: 500px;">
          <el-input v-model="form.consignee" placeholder="长度不超过25个字符"></el-input>
        </div>
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <div style="width: 500px;">
          <el-input v-model="form.phone" placeholder></el-input>
        </div>
      </el-form-item>
      <el-form-item label>
        <el-checkbox-group v-model="form.isDefault">
          <el-checkbox label="设为默认" name="type"></el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">保存</el-button>
      </el-form-item>
    </el-form>

    <AddressTab
      :adressList="adressList"
      @setDefault="setDefault"
      @delAddress="delAddress"
      @updateAddress="updateAddress"
    />
  </div>
</template>
<script>
import AddressTab from "./Address-tab";
import { requireJS } from "@/assets/common";

export default {
  components: {
    AddressTab
  },
  data() {
    //手机号验证
    var checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("手机号不能为空"));
      } else {
        const reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
        if (reg.test(value)) {
          callback();
        } else {
          return callback(new Error("请输入正确的手机号"));
        }
      }
    };
    const self = this;
    return {
      isShowAddressInfo: true,
      form: {
        id: "",
        detailed: "",
        zipCode: "",
        addressInfo: "",
        consignee: "",
        phone: "",
        isDefault: ""
      },
      adressList: [],
      props: {
        lazy: true,
        async lazyLoad(node, resolve) {
          console.log(this);
          const { level } = node;
          var name = "中国";
          if (!node.root) {
            name = node.data.label;
          }
          var ls = await self.searchAll(name);
          resolve(
            ls.map(item => {
              return {
                value: item.name,
                label: item.name,
                leaf: level >= 3
              };
            })
          );
        }
      },
      rules: {
        addressInfo: { required: true, message: "请选择地址", trigger: "change" },
        detailed: {
          required: true,
          message:
            "请输入详细地址信息，如道路、门牌号、小区、楼栋号、单元等信息",
          trigger: "blur"
        },
        zipCode: { required: true, message: "请填写邮编", trigger: "blur" },
        consignee: {
          required: true,
          message: "请填写收货人姓名",
          trigger: "blur"
        },
        phone: [{ required: true, validator: checkPhone, trigger: "blur" }]
      }
    };
  },
  methods: {
    reSetForm() {
      this.form = {
        id: "",
        detailed: "",
        zipCode: "",
        addressInfo: "",
        consignee: "",
        phone: "",
        isDefault: ""
      };
    },
    async onSubmit() {
      await this.$http.post("/index.php/addAddress", {
        ...this.form,
        addressInfo: this.form.addressInfo.join("/"),
        isDefault: this.form.isDefault ? "1" : "0"
      });
      this.$message({
        type: "info",
        message: `添加成功`
      });
      this.reSetForm();
      await this.getData();
    },
    async getData() {
      var { data, code } = await this.$http.get("/index.php/getAddressList");
      this.adressList = data;
      if (code == 4) {
        this.$alert("您还未登录，请先登录", "提醒", {
          confirmButtonText: "确定",
          callback: action => {
            this.$router.push({
              name: "login"
            });
          }
        });
      }
    },
    async setDefault(id) {
      var { data, code } = await this.$http.get(
        `/index.php/setDefault?id=${id}`
      );
      this.$message({
        type: "success",
        message: "设置成功"
      });
      this.getData();
    },
    async delAddress(id) {
      var { data, code } = await this.$http.get(
        `/index.php/delAddress?id=${id}`
      );
      this.$message({
        type: "success",
        message: "删除成功"
      });
      this.getData();
    },
    async updateAddress(data) {
      this.form = {
        id: data.id,
        detailed: data.detailed,
        zipCode: data.zipCode,
        addressInfo: data.addressInfo.split("-"),
        consignee: data.consignee,
        phone: data.phone,
        isDefault: data.isDefault == "1" ? true : false,
        detailed: data.detailed
      };
      this.isShowAddressInfo = false;
      setTimeout(() => {
        this.isShowAddressInfo = true;
      }, 500);
    },
    async getMap() {
      if (this.AMap) {
        return this.AMap;
      } else {
        this.AMap = await requireJS(
          "https://webapi.amap.com/maps?v=1.4.8&key=a42f8fc982b7fcf299e5c4579ab2c419"
        );
        return this.AMap;
      }
    },
    initSearch() {
      return new Promise(async (resolve, reject) => {
        var map = await this.getMap();
        if (this.districtSearch) {
          resolve(this.districtSearch);
        } else {
          map.plugin("AMap.DistrictSearch", () => {
            this.districtSearch = new map.DistrictSearch({
              level: "province",
              subdistrict: 1
            });
            resolve(this.districtSearch);
          });
        }
      });
    },
    async searchAll(name) {
      this.search = await this.initSearch();
      return new Promise((resolve, reject) => {
        this.search.search(name, (status, result) => {
          var list = result.districtList[0]["districtList"];
          resolve(list);
        });
      });
    }
  },
  async created() {
    this.getData();
  }
};
</script>
<style lang="less" scoped>
  .adress-add {
    margin-top: 20px;
  }
</style>
<style lang="less">
  .el-cascader--medium {
    width: 500px;
  }
</style>